package fms.controller;

import fms.core.AutoPosMsgBuilder;
import fms.core.DownRequestAutoPos;
import fms.core.IFilter;
import fms.util.ConfUtil;
import fms.util.ObjectUtil;
import fms.xml.AutoPosResponseXML;
import fms.webservice.Request;
import fms.webservice.WindService;
import fms.webservice.XmlUtil;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.Observable;
import java.util.Observer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/*测试报文
2014-07-21 03:23:47
QU SHAUO9C
.BJSXCXA 300310
DEP
FI 9C8554/AN B-9920/DA ZSYA/DS ZSYA/OF 0706
DT BJS NKG 170707 M78A
-  0531FOB 264,

 */
public class AutoPosController implements IReceiver {
//public class AutoPosController implements Observer {
    private Logger logger = Logger.getLogger(AutoPosController.class);
    ExecutorService pool = Executors.newFixedThreadPool(10);

    private IFilter filter;
    private DownRequestAutoPos downRequestAutoPos;
    private WindService windService;
    private AutoPosMsgBuilder autoPosMsgBuilder;
    private ISender sender;
//    private FmlXmlBuilder fmlXmlBuilder;

    public IFilter getFilter() {
        return filter;
    }

    public void setFilter(IFilter filter) {
        this.filter = filter;
    }

    public DownRequestAutoPos getDownRequestAutoPos() {
        return downRequestAutoPos;
    }

    public void setDownRequestAutoPos(DownRequestAutoPos downRequestAutoPos) {
        this.downRequestAutoPos = downRequestAutoPos;
    }

    public WindService getWindService() {
        return windService;
    }

    public void setWindService(WindService windService) {
        this.windService = windService;
    }

    public AutoPosMsgBuilder getAutoPosMsgBuilder() {
        return autoPosMsgBuilder;
    }

    public void setAutoPosMsgBuilder(AutoPosMsgBuilder autoPosMsgBuilder) {
        this.autoPosMsgBuilder = autoPosMsgBuilder;
    }

    public void setSender(ISender sender) {
        this.sender = sender;
    }

    public Logger getLogger() {
        return logger;
    }

    public void setLogger(Logger logger) {
        this.logger = logger;
    }

    public ISender getSender() {
        return sender;
    }


    public AutoPosController() {
    }


//    public void update(Observable observable, Object arg) {
//        String msg = (String) arg;
//        if (filter.isFilter(msg)) {
//            DealAutoPos dealAutoPosRequest = new DealAutoPos(msg, downRequestAutoPos, windService, autoPosMsgBuilder, sender);
//            pool.execute(dealAutoPosRequest);
//        } else {
//            return;
//        }
//    }

    public void receiveMsg( Object arg) {
        String msg = (String) arg;
        if (filter.isFilter(msg)) {
            DealAutoPos dealAutoPosRequest = new DealAutoPos(msg, downRequestAutoPos, windService, autoPosMsgBuilder, sender);
            pool.execute(dealAutoPosRequest);
        } else {
            return;
        }
    }

    private static class DealAutoPos implements Runnable {
        private Logger logger = Logger.getLogger(DealAutoPos.class);

        // 风温上行回复报文的SMI
        private String replySMI = "";
        private String msg;
        private DownRequestAutoPos downRequestAutoPos;
        private WindService windService;
        private AutoPosMsgBuilder autoPosMsgBuilder;
        private ISender sender;

        public String getReplySMI() {
            return replySMI;
        }

        public void setReplySMI(String replySMI) {
            this.replySMI = replySMI;
        }


        public DownRequestAutoPos getDownRequestAutoPos() {
            return downRequestAutoPos;
        }

        public void setDownRequestAutoPos(DownRequestAutoPos downRequestAutoPos) {
            this.downRequestAutoPos = downRequestAutoPos;
        }

        public WindService getWindService() {
            return windService;
        }

        public void setWindService(WindService windService) {
            this.windService = windService;
        }

        public AutoPosMsgBuilder getAutoPosMsgBuilder() {
            return autoPosMsgBuilder;
        }

        public void setAutoPosMsgBuilder(AutoPosMsgBuilder autoPosMsgBuilder) {
            this.autoPosMsgBuilder = autoPosMsgBuilder;
        }

        public ISender getSender() {
            return sender;
        }

        public void setSender(ISender sender) {
            this.sender = sender;
        }

        public String getMsg() {
            return msg;
        }

        public void setMsg(String msg) {
            this.msg = msg;
        }

        private DealAutoPos(String msg, DownRequestAutoPos downRequestAutoPos, WindService windService, AutoPosMsgBuilder autoPosMsgBuilder, ISender sender) {
            this.msg = msg;
            this.downRequestAutoPos = downRequestAutoPos;
            this.windService = windService;
            this.autoPosMsgBuilder = autoPosMsgBuilder;
            this.sender = sender;

            File fBaseParam = new File(ConfUtil.props.getProperty("baseParamFilePath"));
            final SAXReader readerBaseParam = new SAXReader();
            try {
                final Document paraseRulenDoc = readerBaseParam.read(fBaseParam);
                Element uniqueObject = (Element) paraseRulenDoc.selectSingleNode("/baseParamter/coreService/autoPosController/replySMI");
                this.replySMI = uniqueObject.getText();
            } catch (final DocumentException e) {
                logger.error(e.getMessage());
            }
        }

        public void dealAutoPos(String msg, DownRequestAutoPos downRequestAutoPos, WindService windService, AutoPosMsgBuilder autoPosMsgBuilder, String replySMI, ISender sender) {
            logger.info("接收到mq传来的数据：" + "\r\n" + msg);
            try {
                Request request = downRequestAutoPos.parse(msg);
                logger.info("报文解析完成，向Webservice服务进行风温请求：" + "\r\n" + request.getRequestXML());
                AutoPosResponseXML autoPosResponseXML = windService.getAutoPosition(request);
                logger.info("Webservice返回的数据：" + "\r\n" + XmlUtil.marshallAutoPosResponse(autoPosResponseXML));
                if (!ObjectUtil.isBlank(autoPosResponseXML.getCptname())) {
                    try {
                        String message = autoPosMsgBuilder.builder(autoPosResponseXML, replySMI);
                        logger.info("飞机自动下发航路点请求报文 对应Acars620格式的上行XML回复报文构造完成：" + "\r\n" + message);
                        sender.send(message);
                        logger.info("飞机自动下发航路点请求的回复报文已发出！");
                    } catch (Exception ex) {
                        logger.error("飞机自动下发航路点请求的回复报文组报错误！");
                        return;
                    }
                } else {
                    logger.error("没有符合条件的航路点信息（webservice返回为空），原始报文为：\r\n" + msg);
                }
            } catch (Exception ex) {
                logger.error("飞机自动下发航路点请求处理失败，系统异常：" + ex.toString());
            }

        }

        @Override
        public void run() {
            dealAutoPos(msg, downRequestAutoPos, windService, autoPosMsgBuilder, replySMI, sender);
        }

    }

}